/*********************************************************************/
/*  文件名  LoginImpl.java    　                                        */
/*  程序名  登录域实现                     						     				     */
/*  版本履历   2015/5/5  修改                  刘伟    			                             */
/*         Copyright 2015 LENOVO. All Rights Reserved.               */
/*********************************************************************/
package com.zhaolang.qogir.domain.impl;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.Login;
import com.zhaolang.qogir.server.ClientCallbackImpl;
import com.zhaolang.qogir.server.RadarProxy;
import com.zhaolang.qogir.server.ServerRequestParams;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.Slog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginImpl extends Login {
	private final String TAG = "LoginImpl";
	private Context context;
	private ServerRequestParams params;
	private Handler handler;

	public LoginImpl(Context context) {
		this.context = context;
	}

	@SuppressLint("HandlerLeak")
	@Override
	public void loginAsync(LoginReq paramBean, final BaseCall<LoginResp> call) {
		handler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				if (call != null && !call.cancel) {
					call.call((LoginResp) msg.obj);
				}
			}
		};
		RadarProxy.getInstance(context).startServerData(writeHttpParams(paramBean), new ClientCallbackImpl() {
			@Override
			public void onSuccess(String result) {
				JSONObject jsonObj;
				LoginResp resp = new LoginResp();
				Log.d("Radar", "loginAsync: " + result);
				try {
                    resp = new LoginResp();
                    jsonObj = new JSONObject(result);

                    resp.setStatusCode(jsonObj.optInt("statusCode"));
                    JSONObject jsonObject2 = new JSONObject(jsonObj.optString("message"));
                    resp.setStatus(jsonObject2.optString("status"));

					JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("pd"));
                    if ("SUCCESS".equalsIgnoreCase(jsonObject3.optString("status"))) {
                        resp.setUserId(jsonObject3.optString("shop_id"));
                        String UserId = jsonObject3.optString("shop_id");
                        if (!TextUtils.isEmpty(UserId)) {
                            SharePreCacheHelper.setUserID(context, UserId);
                        }
                    }
//                    radarLogin();
					Message msg = Message.obtain();
					msg.obj = resp;
					handler.sendMessage(msg);
				} catch (JSONException e) {
					e.printStackTrace();
					resp.setStatus("FAILED");
					Log.d("Radar", "JSONException: " + e);
					Message msg = Message.obtain();
					msg.obj = resp;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onFailure(String result) {
				LoginResp resp = new LoginResp();
				resp.setSuccess(false);
				Message msg = new Message();
				msg.obj = resp;
				handler.sendMessage(msg);
				System.out.println(result);
			}
		});
	}

	private void writeLocalContent(String token) {
		HttpConstant.TOKEN = token;
		//RadarProxy.getInstance(context).startLocalData(HttpConstant.getLoginUrl(null), token, null);
		SharePreCacheHelper.setUserToken(context, token);
		Log.d("Radar", "writeLocalContent mytoken: " + HttpConstant.TOKEN);
		Slog.f("Filelog: writeLocalContent mytoken: " + HttpConstant.TOKEN);
	}

	private ServerRequestParams writeHttpParams(LoginReq bean) {
		params = getServerRequest();
		params.setRequestUrl(HttpConstant.getLoginUrl(null));
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("USERNAME", bean.getUsername());
		param.put("SMSCODE", bean.getSmsCode());
		param.put("TOKEN", HttpConstant.TOKEN);
		param.put("FKEY", HttpConstant.getFKEY());
		params.setRequestParam(param);
		params.setRequestEntity(null);
		return params;
	}

	private ServerRequestParams getServerRequest() {
		if (params == null) {
			params = new ServerRequestParams();
		}
		return params;
	}

	private void radarLogin() {
		RadarProxy.getInstance(context).startServerData(writeRadarRegParam(), new ClientCallbackImpl() {
			@Override
			public void onSuccess(String result) {
				JSONObject jsonObj;
				LoginResp resp = null;
				try {
					Log.d("Radar", "radarLogin: " + result);
					resp = new LoginResp();
					jsonObj = new JSONObject(result);

					resp.setStatusCode(jsonObj.optInt("statusCode"));
					JSONObject jsonObject2 = new JSONObject(jsonObj.optString("message"));
					JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("pd"));
					resp.setStatus(jsonObject3.optString("status"));

					if ("SUCCESS".equalsIgnoreCase(jsonObject3.optString("status"))) {
						resp.setUserId(jsonObject3.optString("shop_id"));
						String UserId = jsonObject3.optString("shop_id");
						if (!TextUtils.isEmpty(UserId)) {
							SharePreCacheHelper.setUserID(context, UserId);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
					resp = new LoginResp();
					resp.setStatus("FAILED");
					//resp.setStatusCode(BaseResp.TIMEOUT);
					resp.setSuccess(false);
				}
				Message msg = Message.obtain();
				msg.obj = resp;
				handler.sendMessage(msg);
			}

			@Override
			public void onFailure(String result) {
				LoginResp resp = new LoginResp();
				resp.setStatus("FAILED");
				Message msg = Message.obtain();
				msg.obj = resp;
				//handler.sendMessage(msg);
				System.out.println(result);
			}
		});
	}

	private ServerRequestParams writeRadarRegParam() {
		params = getServerRequest();
		params.setToken(HttpConstant.TOKEN);
//		params.setRequestUrl(HttpConstant.getRadarLoginUrl(null));
		params.setRequestParam(null);
		params.setRequestEntity(null);
		return params;
	}
}
